package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryTypeList() {
        String cacheKey = RedisConstants.CACHE_SHOP_TYPE_LIST_KEY;
        //从 redis 查缓存
        String JsonType = stringRedisTemplate.opsForValue().get(cacheKey);
        // 如果redis存在
        if(StrUtil.isNotBlank(JsonType)){
            List<ShopType> list = JSONUtil.toList(JsonType,ShopType.class);
            return list;
        }
        //若不存在，则根据查数据库
        List<ShopType> typeList = this.query()
                .orderByAsc("sort")
                .list();

        // 数据库不存在就返回错误
        if(typeList == null || typeList.isEmpty()){
            return Collections.emptyList();
        }

        //存进redis去
        stringRedisTemplate.opsForValue().set(cacheKey,JSONUtil.toJsonStr(typeList),CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return typeList;
    }
}
